package zy;

public class piao{
	
    public static void main(String[] args) {
        
        Station station1 = new Station("售票口一");
        Station station2 = new Station("售票口二");
        
        station1.start();
        station2.start();
    }
}

class Station extends Thread {
   
    static int ticket = 5;
   
    static Object ob = "ThisIsATicket";

    public Station(String name) {
        super(name);
    }

    public void run() {
       sell();
    }

    //售卖方法
    public void sell() {
        while (ticket > 0) {
            synchronized (ob) {				
               
                if (ticket > 0) {
                    //窗口二有二分之一的可能是退票
                    if (getName().equals("售票口二") && Math.random() > 0.5 && ticket < 5) {
                        ticket++;
                        System.out.println("退票第" + ticket + "张票");
                    } 
                    else {
                        System.out.println(getName() + "卖了第" + ticket + "张票");
                        ticket--;
                    }

                } 
                else {
                    System.out.println("很抱歉，票卖完了");
                }
            }
            
            try {
                sleep((long) (1000 * Math.random()));
            }
            catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}